package com.chenjiaru.thread.lock;

import com.chenjiaru.thread.util.ThreadUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * 互斥锁（隐式锁，底层实现的）
 */
@Data
@Slf4j
public class SynchronizedDemo {



    public static Integer ticket = 10;

    public static void main(String[] arr) {
        lock();
    }

    /**
     * 没有锁（有线程安全问题）
     */
    private static void nolock() {
        // 10条线程去售票
        for (int i = 0; i < 5; i++) {
            Thread thread = new Thread(() -> {
                while (true) {
                    if (SynchronizedDemo.ticket <= 0) {
                        break;
                    }
                    log.info("出售一张票，余票={}", --SynchronizedDemo.ticket);
                    ThreadUtil.mySleep(200);
                }
            });
            thread.setName("售票员"+i);
            thread.start();
        }
    }

    /**
     * 使用synchronized互斥锁保证了线程安全
     */
    private static void lock() {
        for (int i = 0; i < 5; i++) {
            Thread thread = new Thread(() -> {
                while (true) {
                    synchronized (SynchronizedDemo.ticket) {
                        if (SynchronizedDemo.ticket <= 0) {
                            break;
                        }
                        log.info("出售一张票，余票={}", --SynchronizedDemo.ticket);
                        ThreadUtil.mySleep(200);
                    }
                }
            });
            thread.setName("售票员"+i);
            thread.start();
        }
    }


}
